<!-- components/TabComponent.vue -->
<template>
	<view class="tab-bar" :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }">
		<view v-for="tab in tabs" :key="tab.key" class="tab-bar-item" @click="handleTabClick(tab)"
			:class="{ 'tab-bar-item--active': isActive(tab) }">
			<image class="tab-bar-icon" :src="isActive(tab) ? tab.selectedIconPath : tab.iconPath" :alt="tab.title" />
			<text class="tab-bar-text" :class="{ 'tab-bar-text--active': isActive(tab) }">
				{{ tab.title }}
			</text>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getAppEnum } from "@/utils/appDataEnum"


import {
	useTabStore
} from '@/stores/tabs'
import router from '@/router'
const tabStore = useTabStore()

const props = defineProps({
	tabs: {
		type: Array,
		required: true,
		default: () => []
	}
})

const emit = defineEmits(['change'])

const safeAreaInsets = ref({ bottom: 0 })

// 获取当前页面路径，用于匹配 active
const currentPagePath = computed(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	return currentPage?.route || ''
})

const isActive = (tab) => {
	const userRole = getApp()[getAppEnum.CurrentRole];
	const _key = tab.key || userRole;
	tabStore.setActive(_key)
	return tab.path === currentPagePath.value
}

const handleTabClick = (tab) => {
	console.log("tabCLick:", tab)
	const userRole = getApp()[getAppEnum.CurrentRole];
	if (tab.key == "mine" && userRole == "default") {
		router.push({
			name: "login_main"
		})
		return;
	}
	emit('change', tab) // 向父组件发射事件

}

onMounted(() => {
	const info = uni.getSystemInfoSync()
	safeAreaInsets.value = info.safeAreaInsets || { bottom: 0 }
})
</script>

<style lang="less" scoped>
.tab-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	height: 140rpx;
	background-color: #fff;
	border-top: 1rpx solid #f1f1f1;
	z-index: 999;
	transform: translateZ(0);
}

.tab-bar-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 10rpx;
}

.tab-bar-icon {
	width: 48rpx;
	height: 48rpx;
	margin-bottom: 6rpx;
}

.tab-bar-text {
	font-size: 22rpx;
	color: #666;
	transition: color 0.2s ease;
}

.tab-bar-text--active {
	color: #ff2442;
}
</style>